<template>
  <div class="p-2">
    <el-row :gutter="20">
      <el-col :span="8" :xs="24">
        <el-card class="box-card" v-show="!dialog.visible">
          <div>
            <el-button v-if="!infoData.bankName" type="primary" @click="handleAdd" >新增</el-button>
            <el-button v-else type="primary" @click="handleUpdate(userBankList[0])" >修改</el-button>
          </div>
          <div>
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                开户银行
                <div class="pull-right">{{ infoData.bankName }}</div>
              </li>
              <li class="list-group-item">
                账户名称
                <div class="pull-right">{{ infoData.cardName }}</div>
              </li>
              <li class="list-group-item">
                银行卡号
                <div class="pull-right">{{ infoData.cardNumber }}</div>
              </li>
              <li class="list-group-item" style="height: 240px; line-height: 240px;">
                银行账户信息证明
                <div class="pull-right">
                  <image-preview style="display: block;" v-if="infoData.cardImage" :src="infoData.cardImage" :width="200" :height="200" />
                </div>
              </li>
              <li class="list-group-item">
                可否开具服务发票
                <div class="pull-right">{{ infoData.invoice == '1' ? '是' : '否' }}</div>
              </li>
              <li class="list-group-item">
                可否配合增加发票项
                <div class="pull-right">{{ infoData.addInvoice == '1' ? '是' : '否' }}</div>
              </li>
            </ul>
          </div>
        </el-card>
        <el-card v-show="dialog.visible">
          <!-- 添加或修改银行信息对话框 -->
          <el-form ref="userBankFormRef" :model="form" :rules="rules" label-width="150px">
            <el-form-item label="开户银行" prop="bankName">
              <el-input v-model="form.bankName" placeholder="请输入开户银行" clearable/>
            </el-form-item>
            <el-form-item label="账户名称" prop="cardName">
              <el-input v-model="form.cardName" placeholder="请输入账户名称" clearable/>
            </el-form-item>
            <el-form-item label="银行账号" prop="cardNumber">
              <el-input v-model="form.cardNumber" placeholder="请输入银行账号" clearable/>
            </el-form-item>
            <el-form-item label="银行账户信息证明" prop="cardImage">
              <!-- <el-input v-model="form.cardImage" placeholder="请输入银行账户信息证明" /> -->
              <image-upload :limit="1" v-model="form.cardImage" />
            </el-form-item>
            <el-form-item label="可否开具服务发票" prop="invoice">
              <el-radio-group v-model="form.invoice" >
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="可否配合增加发票项" prop="addInvoice">
              <el-radio-group v-model="form.addInvoice" >
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-card>
      </el-col>
      <!-- <el-col :span="18" :xs="24"> </el-col> -->
    </el-row>
  </div>
</template>

<script setup name="UserBank" lang="ts">
import { listUserBank, getUserBank, delUserBank, addUserBank, updateUserBank } from '@/api/system/userBank';
import { UserBankVO, UserBankQuery, UserBankForm } from '@/api/system/userBank/types';
import { validateSpaceAndEmoji } from '@/utils/validate'


const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const userBankList = ref<UserBankVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const infoData: UserBankForm = reactive({});
const queryFormRef = ref<ElFormInstance>();
const userBankFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: UserBankForm = {
  id: undefined,
  userId: undefined,
  bankName: undefined,
  cardName: undefined,
  cardNumber: undefined,
  cardImage: undefined,
  invoice: undefined,
  addInvoice: undefined,
  createdAt: undefined,
  updatedAt: undefined
};
const data = reactive<PageData<UserBankForm, UserBankQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    userId: undefined,
    bankName: undefined,
    cardName: undefined,
    cardNumber: undefined,
    cardImage: undefined,
    invoice: undefined,
    addInvoice: undefined,
    createdAt: undefined,
    updatedAt: undefined,
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
    bankName: [{ required: true, message: '开户银行不能为空', trigger: 'blur' },{ validator: validateSpaceAndEmoji, }],
    cardName: [{ required: true, message: '姓名不能为空', trigger: 'blur' },{ validator: validateSpaceAndEmoji, }],
    cardNumber: [{ required: true, message: '银行账号不能为空', trigger: 'blur' },{ validator: validateSpaceAndEmoji, }],
    cardImage: [{ required: true, message: '银行账户信息证明不能为空', trigger: 'blur' }],
    invoice: [{ required: true, message: '可否开具服务发票不能为空', trigger: 'blur' }],
    addInvoice: [{ required: true, message: '可否配合增加发票项不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询银行信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listUserBank(queryParams.value);
  userBankList.value = res.rows;
  total.value = res.total;
  Object.assign(infoData, res.rows[0]);
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  userBankFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserBankVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  dialog.visible = true;
  dialog.title = '添加银行信息';
  nextTick(() => {
    reset();
  });
};

/** 修改按钮操作 */
const handleUpdate = (row?: UserBankVO) => {
  loading.value = true;
  dialog.visible = true;
  dialog.title = '修改银行信息';
  nextTick(async () => {
    reset();
    const _id = row?.id || ids.value[0];
    const res = await getUserBank(_id);
    loading.value = false;
    Object.assign(form.value, res.data);
  });
};

/** 提交按钮 */
const submitForm = () => {
  userBankFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateUserBank(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addUserBank(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: UserBankVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除银行信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delUserBank(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/userBank/export',
    {
      ...queryParams.value
    },
    `userBank_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
